<template>
  <BasicModal
    v-bind="$attrs"
    title="onlyOffice预览"
    @register="registerModal"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
    :defaultFullscreen="true"
    :canFullscreen="false"
    :showCancelBtn="false"
    :showOkBtn="false"
    :width="800"
    :height="600"
  >
    <DocumentEditor
      id="docEditor"
      :documentServerUrl="globSetting.onlyOfficeUrl"
      :config="config"
      :events_onDocumentReady="onDocumentReady"
      :onLoadComponentError="onLoadComponentError"
  /></BasicModal>
</template>

<script setup lang="ts">
  import { useGlobSetting } from '/@/hooks/setting';
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { DocumentEditor } from '@onlyoffice/document-editor-vue';
  import { GetOnlyOfficeConfig } from '/@/api/demo/document';

  const globSetting = useGlobSetting();

  const [registerModal, { closeModal }] = useModalInner((data) => {
    dataList.value = data.configList;
    GetOnlyOfficeConfig(
      dataList.value.oId,
      dataList.value.version,
      dataList.value.userId,
      dataList.value.mode,
    ).then((res) => {
      config.value = res;
    });
  });

  const handleSubmit = () => {
    handleCancel();
  };

  const handleCancel = () => {
    config.value = {};
    closeModal();
  };

  // config 配置
  const config = ref({});
  const dataList = ref<any>({});

  const onDocumentReady = () => {
    console.log('onDocumentReady');
  };

  const onLoadComponentError = (errorCode: number, errorDescription: string) => {
    switch (errorCode) {
      case -1:
        console.error('未知错误（-1）：可能是 config 配置错误或初始化失败。', errorDescription);
        break;
      case -2:
        console.error(
          '加载 DocsAPI 失败（-2）：请检查 documentServerUrl 是否正确，是否能访问 api.js。',
          errorDescription,
        );
        break;
      case -3:
        console.error(
          'DocsAPI 未定义（-3）：可能是文档服务 JS 没加载，或 CSP 限制。',
          errorDescription,
        );
        break;
      default:
        console.error(`未定义错误码（${errorCode}）：`, errorDescription);
        break;
    }
  };
</script>
